package com.atguigu.gulimall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * <p>
 * 跨域配置类
 * </p>
 *
 * @authoer fangXK
 * @since 2020-07-23
 */
@Configuration
public class GulimallCorsConfiguration {

    //只需要将WebFilter放到容器中就可以起作用
    @Bean
    public CorsWebFilter corsWebFilter(){
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration=new CorsConfiguration();
        //1.配置跨域
        corsConfiguration.addAllowedHeader("*");    //允许哪些请求头进行跨域
        corsConfiguration.addAllowedMethod("*");    //允许哪些请求方法进行跨域
        corsConfiguration.addAllowedOrigin("*");    //允许哪些请求来源进行跨域
        corsConfiguration.setAllowCredentials(true);//允许跨域请求携带cookie，保证cookie不丢失
        //拦截所有的请求进行跨域访问配置，将配置注册到跨域源上
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}
